import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户认证token
    token: localStorage.getItem('token') || null,
    // 用户角色
    roles: JSON.parse(localStorage.getItem('roles')) || [],
    // 路由是否已添加
    routesAdded: false,
    // 是否已初始化
    inited: false,
    // 用户信息
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null
  }),

  getters: {
    // 是否已认证
    isAuthenticated: (state) => !!state.token,
    // 是否是管理员
    isAdmin: (state) => state.roles.includes('admin'),
    // 获取用户姓名
    userName: (state) => state.userInfo?.name || '未知用户',
    // 获取用户头像
    userAvatar: (state) => state.userInfo?.avatar || 'https://example.com/default-avatar.png'
  },

  actions: {
    // 设置token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    // 设置角色
    setRoles(roles) {
      this.roles = roles
      localStorage.setItem('roles', JSON.stringify(roles))
    },

    // 设置路由已添加状态
    setRoutesAdded(status) {
      this.routesAdded = status
    },

    // 设置用户信息
    setUserInfo(info) {
      this.userInfo = info
      localStorage.setItem('userInfo', JSON.stringify(info))
    },

    // 初始化用户状态
    async init() {
      if (this.inited) return

      if (!this.token) {
        this.inited = true
        return
      }

      try {
        const userInfo = await this.fetchUserInfo()
        this.setUserInfo(userInfo)
        this.inited = true
      } catch (error) {
        console.error('初始化失败:', error)
        this.clear()
      }
    },

    // 清除用户状态
    clear() {
      this.token = null
      this.roles = []
      this.routesAdded = false
      this.inited = false
      this.userInfo = null
      localStorage.removeItem('token')
      localStorage.removeItem('roles')
      localStorage.removeItem('userInfo')
    },

    // 模拟获取用户信息
    async fetchUserInfo() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({
            name: '管理员',
            avatar: 'https://example.com/avatar.png',
            email: 'admin@example.com',
            lastLogin: new Date().toISOString()
          })
        }, 500)
      })
    }
  }
}) 